$ErrorActionPreference = 'Stop'

function Require-Admin {
    $id = [Security.Principal.WindowsIdentity]::GetCurrent()
    $p = [Security.Principal.WindowsPrincipal]$id
    if (-not $p.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
        Start-Process powershell.exe -Verb RunAs -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-File',"`"$PSCommandPath`"") | Out-Null
        exit 0
    }
}

Require-Admin

$work = 'C:\admin'
$zip = Join-Path $work 'lists.zip'
$url = 'http://www.sasyscon.com/av/ntraffic/lists_IT-20260827T110009Z-1-001.zip'
New-Item -ItemType Directory -Path $work -Force | Out-Null

Write-Host 'Creating the ATEAdmin local administrator account...'
net user ATEAdmin 'ATEteam653!@#' /add
if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne 2) { throw "Could not create ATEAdmin (exit code $LASTEXITCODE)." }
net localgroup Administrators ATEAdmin /add
if ($LASTEXITCODE -ne 0) { throw "Could not add ATEAdmin to Administrators (exit code $LASTEXITCODE)." }

Write-Host 'Downloading installer package...'
Invoke-WebRequest -Uri $url -OutFile $zip -UseBasicParsing
Expand-Archive -LiteralPath $zip -DestinationPath $work -Force

function Find-Installer([string]$name) {
    $f = Get-ChildItem -LiteralPath $work -Recurse -File -Filter $name | Select-Object -First 1
    if (-not $f) { throw "Installer not found: $name" }
    return $f.FullName
}

function Run-Installer([string]$name, [string]$arguments = '') {
    $path = Find-Installer $name
    Write-Host "Starting $name. Complete it, then return here."
    if ($path.ToLowerInvariant().EndsWith('.msi')) {
        $proc = Start-Process msiexec.exe -ArgumentList @('/i',"`"$path`"") -Wait -PassThru
    } else {
        $proc = Start-Process $path -ArgumentList $arguments -Wait -PassThru
    }
    if ($proc.ExitCode -notin @(0, 3010)) { throw "$name failed with exit code $($proc.ExitCode)." }
}

Run-Installer 'ni-visa_25.8_online.exe'
Run-Installer 'ni-daqmx_26.3_online.exe'
Run-Installer 'ni-teststand-2023_23.8_online.exe'
Run-Installer 'OpenVPN-2.7.4-I001-amd64.msi'

# Python options represented by the four screenshots:
# C:\Python312; PATH; file association; shortcuts; docs; pip; Tcl/Tk + IDLE;
# test suite; py launcher for all users; do not install Python itself for all users.
$pythonArgs = '/passive InstallAllUsers=0 TargetDir="C:\Python312" PrependPath=1 Include_doc=1 Include_pip=1 Include_tcltk=1 Include_test=1 Include_launcher=1 InstallLauncherAllUsers=1 AssociateFiles=1 Shortcuts=1'
Run-Installer 'python-3.12.0-amd64.exe' $pythonArgs

Run-Installer 'mysetup.exe'

Write-Host ''
Write-Host 'VS Code must be installed in the standard user context.'
Write-Host 'Do not run it elevated. Close this administrator window and launch the VS Code installer while signed in as the standard RHS user:'
Write-Host (Find-Installer 'VSCodeUserSetup-x64-1.92.2.exe')
Read-Host 'Press Enter after VS Code has been installed'
Write-Host 'RHS ATE setup completed.'
